 var searchApp = angular.module("searchApp", []);
//实时监听输入value
searchApp.directive('ngInput', [function () {
    return {
        restrict: 'A',
        require: '?ngModel',
        link: function(scope, element, attrs) {
            element.on('input',oninput);
            scope.$on('$destroy',function(){//销毁的时候取消事件监听
                element.off('input',oninput);
            });
            function oninput(event){
                scope.$evalAsync(attrs['ngInput'],{$event:event,$value:this.value});
            }
        }
    }
}]);

searchApp.controller("searchController", function($scope,$stateParams,$rootScope, $window, scCodeService, Popup, $location) {   
    document.getElementById("loadingToast1").style.display = "none";
    $scope.focus = function(){
        setTimeout(function(){
            document.getElementById("name_focus").focus();
        },300)
    };
    $scope.focus();
    var coords = JSON.parse(localStorage.getItem("coords"));
    var userId = localStorage.getItem("userId");
    //获取当前城市
    $scope.currentId = $stateParams.currentId;
    if($scope.currentId == 0){
        $scope.currentCity = JSON.parse(localStorage.getItem("currentCity"));
    }else{
        $scope.currentCity = JSON.parse(localStorage.getItem("city"));     
    }
    if($scope.currentCity==null||$scope.currentCity==""||$scope.currentCity==undefined){
        $scope.currentCity = {
            cityId:"510100",
            cityName:"成都",
            provinceName: "四川省"
        }
    } 
    //清空输入框
    $scope.searchEmpty = function() {   
            $location.path("index_");
    }
    //根据输入的关键字进行第三方关联地址查询
    $scope.getCognateAddress = function(value) {
            AMap.plugin('AMap.Autocomplete', function() { //回调函数
                //实例化Autocomplete
                var autoOptions = {
                    city: $scope.currentCity.cityId //城市，默认全国
                };
                autocomplete = new AMap.Autocomplete(autoOptions);
                autocomplete.search(value, function(status, result) {
                    //TODO:开发者使用result自己进行下拉列表的显示与交互功能
                    if (status != "error") {
                        if (status != "no_data") {
                             $scope.$apply(function(){
                               $scope.CognateAddress = result.tips; 
                             })
                            
                        }
                    }
                });
            })
    }
    //历史记录
    $scope.recordHistory = function(resultList){
            $scope.historyList = JSON.parse(localStorage.getItem("resultList"))||[];
            $scope.historyList.splice(0,0,resultList);
            var len = $scope.historyList.length;
            if(len > 10){
                $scope.historyList = $scope.historyList.slice(0,10);
            }
            $scope.historyList = $scope.historyList;
            if(!!$scope.historyList){
                //将对象元素转换成字符串以作比较
                function obj2key(obj, keys){
                    var n = keys.length,
                        key = [];
                    while(n--){
                        key.push(obj[keys[n]]);
                    }
                    return key.join('|');
                }
                //去重操作
                function uniqeByKeys(array,keys){
                    var arr = [];
                    var hash = {};
                    for (var i = 0, j = array.length; i < j; i++) {
                        var k = obj2key(array[i], keys);
                        if (!(k in hash)) {
                            hash[k] = true;
                            arr .push(array[i]);
                        }
                    }
                    return arr ;
                }
                $scope.historyList = uniqeByKeys($scope.historyList,['name']);
            }
            localStorage.setItem("resultList",JSON.stringify($scope.historyList));
    }
    $scope.historyList = JSON.parse(localStorage.getItem("resultList"));
    //清空历史
    $scope.clearHistoryList = function() {
            $scope.historyList = [];
            localStorage.removeItem("resultList");
            $scope.historyList = JSON.parse(localStorage.getItem("resultList"));
    }
    //键盘搜索
    $scope.myFunctSearch = function(event){
        if(event.which === 13){
            if($scope.searchVal==""||$scope.searchVal==null||$scope.searchVal==undefined){
                Popup.notice('请输入搜索内容', 2000, function () {
                    
                });
            }else{
                document.getElementById("loadingToast1").style.display = "block";
                var resultList = {
                    "id": "",
                    "name": $scope.searchVal,
                    "district": "",
                    "adcode": "",
                    "location": "",
                    "address": "",
                    "typecode": ""
                };
                $scope.recordHistory(resultList);
                //根据城市code查询站点列表
                $scope.getStationByName = function(postData){
                    var postData = {
                        stationName:$scope.searchVal,
                        latitude:coords.latitude,
                        longtitude:coords.longtitude
                    }
                    scCodeService.getStationByName(postData).then(function(data){
                        if(data.code == "200"){
                            document.getElementById("loadingToast1").style.display = "none";
                            if(!!data.data.length){
                                $scope.searchResult = data.data;
                                localStorage.setItem("searchResult", JSON.stringify($scope.searchResult));                            
                                $location.path("/searchResult");
                            }else{
                                document.getElementById("loadingToast1").style.display = "none";
                                $location.path("/noResult/" + $scope.searchVal);               
                            }
                        }
                    })
                }
                $scope.getStationByName();
            }
            
        }
    }
    //搜索结果
    $scope.goStationList = function(resultList,location,name){
        $scope.recordHistory(resultList);
        //根据输入关键字搜索
        document.getElementById("loadingToast1").style.display = "block";
        if(location == ""||location == undefined||location==null||location.length){
            //alert("name");
            $scope.getStationByName = function(postData){
                var postData = {
                    stationName: name,
                    latitude:coords.latitude,
                    longtitude:coords.longtitude
                }
                scCodeService.getStationByName(postData).then(function(data){
                    
                    if(data.code == "200"){
                        document.getElementById("loadingToast1").style.display = "none";
                        if(!!data.data.length){
                            $scope.searchResult = data.data;
                            localStorage.setItem("searchResult", JSON.stringify($scope.searchResult));
                            $location.path("/searchResult");
                        }else{
                            $location.path("/noResult/" + name);                   
                        }
                    }else{
                        document.getElementById("loadingToast1").style.display = "none";
                        Popup.notice('服务器错误', 3000, function () {
                            
                        });
                    }
                })
            }
            $scope.getStationByName();
        //根据坐标搜索
        }else{
            //alert("坐标");
            $scope.getStationByCoordinate = function(){
                var postData = {
                    latitude:location.lat,
                    longtitude:location.lng,
                    locaLatitude:coords.latitude,
                    locaLongtitude:coords.longtitude,
                    number:"30" 
                }
                scCodeService.getStationByCoordinate(postData).then(function(data){
                    if(data.code == "200"){
                        document.getElementById("loadingToast1").style.display = "none";
                        if(!!data.data.length){
                            $scope.searchResult = data.data;
                            localStorage.setItem("searchResult", JSON.stringify($scope.searchResult));
                            $location.path("/searchResult");
                        }else{
                            $location.path("/noResult/" + $scope.searchVal);
                        }
                    }else{
                        document.getElementById("loadingToast1").style.display = "none";
                        Popup.notice('服务器错误', 3000, function () {
                            
                        });
                    }
                })
            }
            $scope.getStationByCoordinate();

        }
    }

})

//切换城市
searchApp.controller("checkCityController", function($scope, $element, $rootScope, $window, scCodeService, Popup, $location) {
    //当前城市
    $scope.currentCity = JSON.parse(localStorage.getItem("city"));
    if($scope.currentCity===null||$scope.currentCity===undefined||$scope.currentCity===""){
        $scope.currentCity = {
            cityId:"510100",
            cityName:"成都",
            provinceName: "四川省"
        }
    }
    //获取城市列表
    $scope.getCityList = function() {
        scCodeService.getCityList().then(function(data) {
            if (data.code == "200") {
                if (data.data) {
                $scope.cityList = data.data;
                $scope.twentySix = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"];
                };
            } else {
                Popup.notice('获取城市列表失败', 3000, function() {
                    
                });
            }
        })
    }
    $scope.getCityList();
    //点击某个城市，储存城市代码和名称并跳转到搜索界面
    $scope.subCurrentCity = function(code, name) {
        $scope.currentCity = { cityId: code, cityName: name };
        localStorage.setItem("currentCity", JSON.stringify($scope.currentCity));
        $scope.currentId = 0;
        //alert("$scope.currentCity");
        $location.path("/search/" + $scope.currentId);
    }
    //点击字母跳转到指定城市列表
    $scope.goToCityList=function (letter) {
        var scrollt = document.getElementById(letter).offsetTop;
        window.scrollTo(0, scrollt);
    }
    //滑动字母跳转到对应的字母城市列表
    $element.bind("touchstart", onTouchStart);

    function onTouchStart(event) {
        $element.bind("touchmove", onTouchMove);
        onTouchMove(event);
    }

    function onTouchMove(event) {
        var method = $element.attr("ng-touchmove");
        //$scope.$apply(method);
        var touch = event.touches[0];
        //alert("x:"+Number(touch.clientX)+",y:"+Number(touch.clientY));
        var element = document.elementFromPoint(Number(touch.clientX), Number(touch.clientY));
        //alert(JSON.stringify(element));
        //var element=touch.target;
        var datastr = element.getAttribute("data");
        //alert(datastr)
        if (datastr != null && datastr != "null" && datastr.match(/^([A-Z])+$/)) {
            var scrollt = document.getElementById(datastr).offsetTop;
            window.scrollTo(0, scrollt);
            //window.location.href="#/checkCity#"+datastr;
        }
    }

})
